package com.fmatos.amazingwallpapers.image.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;

import javax.inject.Inject;

import android.util.Log;

public class CloudHelper {

	private static final String TAG = CloudHelper.class.getSimpleName();

	private static final int TIMEOUT_MS = 5000;

	public URLConnection connectToUrl(String url) {
		
		URL u = null;
		try {
			u = new URL(url);
		} catch (MalformedURLException e1) {
		
			e1.printStackTrace();
		}

        int tries = 4;
        int code = 301;
        URLConnection conn = null;
        while (tries > 0 && code/100 == 3) {
        	conn = null;
        	tries --;
        	try {
        		if ( u != null ) {
        			
        			conn = u.openConnection();
        			conn.setConnectTimeout(TIMEOUT_MS); // this is not doing what I want
        			conn.setReadTimeout(TIMEOUT_MS);
        			conn.addRequestProperty("Accept-Encoding", "gzip");
        			((HttpURLConnection)conn).setInstanceFollowRedirects(false);//Required        	
        			code =((HttpURLConnection)conn).getResponseCode(); // this says it will throw a SocketTimeoutException but I don't see it
        		}
        	} catch (SocketTimeoutException e) {
        		Log.w(TAG,"Socket timeout exception url=" + u + " ==== " + e.getMessage());
        		code = 500;
        		conn = null;
        		break;
        	} catch (SocketException e) {
        		// TODO timeouts also throw SocketException
        		Log.w(TAG,"Socket exception, are you behind a firewall? url=" + u + " ====" + e.getMessage()) ;
        		conn = null;
				code = -1;
				break;
			} catch (IOException e) {
				Log.w(TAG,"IOException, I dunno whats happening url=" + u + " ====" + e.getMessage()) ;
				// comment: if you're having unknownhostexception in the AVD, try restarting it or creating a new one
				conn = null;
				code = -1;
				break;
			}
    		
    		if (code/100 == 3) {
    			Log.d(TAG,"tries = " + tries + " url=" + u);
    			String loc = conn.getHeaderField("Location");
    			try {
					u = new URL(loc);
				} catch (MalformedURLException e) {
					u = null;
				}
    		}

        }
        
        try {
        	if ( conn != null ) {
        		conn.connect();
        	} else {
        		Log.w(TAG,"Could find connection to " + url);
        	}
		} catch (IOException e) {	
			e.printStackTrace();
			conn = null;
		}
//        Log.d(TAG,"Connected with " + (4-tries) + " tries to " + url);
        
		return conn;
	}
	
	public InputStream downloadImage(String url) {

		if ( url == null ) {
			return null;
		}
		
		Log.d(TAG,"Downloading begins " + url);

		URLConnection connection = connectToUrl(url);
		
		try {
			if ( connection != null ) {
				return connection.getInputStream();
			} else {
				Log.e(TAG,"Failing downloading url " + url);
			}
		} catch (IOException e) {
			Log.e(TAG,"Failing downloading url " + url + " ==> " + e.toString());
		}
		
		return null;
	}
	
	public String getString() {
		return null;
	}
	
	
	/**
	 * Reads the full stream from a connection and returns as a StringBuilder
	 * @param connection
	 * @return
	 */
	public StringBuilder getStringFromConnection(URLConnection connection) {
		if ( connection == null ) {
			Log.w(TAG,"Got null connection downloading album");
			return null;
		}

		StringBuilder builder = new StringBuilder();
        try {
    		InputStream content = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
			while ((line = reader.readLine()) != null) {
			  builder.append(line);
			}
		} catch (IOException e) {
			Log.w(TAG,"Could not download album, error = " + e );
		}

//        Log.v(TAG,builder.toString());
        
        return builder;
	}
}
